import React, { useState } from 'react';
import { 
  Card, Tabs, Button, Form, InputNumber, message, 
  Spin, Typography, Alert, Divider, Image, Result 
} from 'antd';
import { LineChartOutlined, BarChartOutlined, FileTextOutlined } from '@ant-design/icons';
import api from '../../utils/api';

const { Title, Paragraph, Text } = Typography;
const { TabPane } = Tabs;

const ICAAnalysis = () => {
  const [loading, setLoading] = useState(false);
  const [modelTrained, setModelTrained] = useState(false);
  const [resultFigures, setResultFigures] = useState([]);
  const [contributionFigures, setContributionFigures] = useState([]);
  const [diagnosticReport, setDiagnosticReport] = useState('');
  const [activeTab, setActiveTab] = useState('1');
  const [trainError, setTrainError] = useState('');
  
  // 训练模型
  const handleTrainModel = async (values) => {
    setLoading(true);
    setTrainError('');
    
    try {
      const response = await api.trainICA(values);
      setResultFigures(response.data.figures || []);
      setModelTrained(true);
      message.success('ICA模型训练成功');
      setActiveTab('2'); // 自动切换到结果标签页
    } catch (error) {
      console.error('训练失败:', error);
      let errorMsg = '模型训练失败';
      
      if (error.response && error.response.data) {
        errorMsg = error.response.data.message || errorMsg;
      }
      
      setTrainError(errorMsg);
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };
  
  // 获取贡献图
  const handleGetContribution = async () => {
    if (!modelTrained) {
      message.warning('请先训练模型');
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await api.getICAContribution();
      if (response.data.message === '未检测到异常点') {
        message.info('未检测到异常点');
      } else {
        setContributionFigures(response.data.figures || []);
        message.success('贡献图加载成功');
      }
      setActiveTab('3'); // 自动切换到贡献图标签页
    } catch (error) {
      console.error('获取贡献图失败:', error);
      message.error('获取贡献图失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 获取诊断报告
  const handleGetDiagnosis = async () => {
    if (!modelTrained) {
      message.warning('请先训练模型');
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await api.getICADiagnosis();
      setDiagnosticReport(response.data.report);
      message.success('诊断报告生成成功');
      setActiveTab('4'); // 自动切换到诊断报告标签页
    } catch (error) {
      console.error('获取诊断报告失败:', error);
      message.error('获取诊断报告失败');
    } finally {
      setLoading(false);
    }
  };
  
  const handleTabChange = (key) => {
    setActiveTab(key);
  };
  
  return (
    <div>
      <Title level={2}>独立成分分析 (ICA)</Title>
      <Paragraph>
        独立成分分析是一种用于分离混合信号的统计方法，特别适用于线性混合模型的盲源分离。在工业过程中，ICA可以帮助识别潜在的故障模式和异常情况。
      </Paragraph>
      
      <Card>
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="模型训练" key="1">
            <div style={{ maxWidth: '600px', margin: '0 auto' }}>
              <Title level={4}>模型参数配置</Title>
              <Paragraph>
                请设置独立成分的数量。组件数量决定了ICA模型将数据分解为多少个独立信号。
              </Paragraph>
              
              {trainError && (
                <Alert
                  message="训练错误"
                  description={trainError}
                  type="error"
                  showIcon
                  style={{ marginBottom: '16px' }}
                />
              )}
              
              <Form
                onFinish={handleTrainModel}
                initialValues={{ n_components: 5 }}
                layout="vertical"
              >
                <Form.Item
                  name="n_components"
                  label="独立成分数量"
                  rules={[{ required: true, message: '请输入组件数量' }]}
                >
                  <InputNumber min={2} max={100} style={{ width: '100%' }} />
                </Form.Item>
                
                <Form.Item>
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    loading={loading}
                    icon={<LineChartOutlined />}
                    block
                  >
                    开始训练
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </TabPane>
          
          <TabPane tab="训练结果" key="2" disabled={!modelTrained}>
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin size="large" tip="加载结果中..." />
              </div>
            ) : resultFigures.length > 0 ? (
              <div>
                <Title level={4}>训练完成</Title>
                <Paragraph>
                  模型训练成功，下面是训练结果的可视化展示：
                </Paragraph>
                
                <Divider />
                
                {resultFigures.map((figure, index) => (
                  <div key={index} style={{ marginBottom: '24px' }}>
                    <Title level={5}>{figure.title}</Title>
                    <Image
                      src={`data:image/png;base64,${figure.image_data}`}
                      alt={figure.title}
                      style={{ maxWidth: '100%' }}
                    />
                  </div>
                ))}
                
                <Divider />
                
                <div style={{ marginTop: '24px', textAlign: 'center' }}>
                  <Button 
                    type="primary" 
                    onClick={handleGetContribution}
                    icon={<BarChartOutlined />}
                  >
                    查看贡献图
                  </Button>
                  
                  <Button 
                    style={{ marginLeft: '16px' }} 
                    onClick={handleGetDiagnosis}
                    icon={<FileTextOutlined />}
                  >
                    生成诊断报告
                  </Button>
                </div>
              </div>
            ) : (
              <Result
                status="info"
                title="暂无结果"
                subTitle="请先训练模型以查看结果"
              />
            )}
          </TabPane>
          
          <TabPane tab="贡献图分析" key="3" disabled={!modelTrained}>
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin size="large" tip="生成贡献图..." />
              </div>
            ) : contributionFigures.length > 0 ? (
              <div>
                <Title level={4}>贡献图分析</Title>
                <Paragraph>
                  贡献图显示了各个变量对异常点贡献的大小，帮助定位故障原因。
                </Paragraph>
                
                <Divider />
                
                {contributionFigures.map((figure, index) => (
                  <div key={index} style={{ marginBottom: '24px' }}>
                    <Title level={5}>{figure.title}</Title>
                    <Image
                      src={`data:image/png;base64,${figure.image_data}`}
                      alt={figure.title}
                      style={{ maxWidth: '100%' }}
                    />
                  </div>
                ))}
              </div>
            ) : (
              <div>
                <Result
                  status="info"
                  title="暂无贡献图"
                  subTitle="点击下方按钮生成贡献图"
                  extra={
                    <Button 
                      type="primary" 
                      onClick={handleGetContribution}
                      icon={<BarChartOutlined />}
                    >
                      生成贡献图
                    </Button>
                  }
                />
              </div>
            )}
          </TabPane>
          
          <TabPane tab="诊断报告" key="4" disabled={!modelTrained}>
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin size="large" tip="生成诊断报告..." />
              </div>
            ) : diagnosticReport ? (
              <div>
                <Title level={4}>故障诊断报告</Title>
                <Paragraph>
                  基于ICA分析结果的自动故障诊断报告：
                </Paragraph>
                
                <Card style={{ marginTop: '16px', whiteSpace: 'pre-wrap' }}>
                  {diagnosticReport}
                </Card>
              </div>
            ) : (
              <div>
                <Result
                  status="info"
                  title="暂无诊断报告"
                  subTitle="点击下方按钮生成诊断报告"
                  extra={
                    <Button 
                      type="primary" 
                      onClick={handleGetDiagnosis}
                      icon={<FileTextOutlined />}
                    >
                      生成诊断报告
                    </Button>
                  }
                />
              </div>
            )}
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default ICAAnalysis; 